import redis
from app.config import settings

# 创建Redis连接池
redis_pool = redis.ConnectionPool(
    host=settings.REDIS_HOST,
    port=settings.REDIS_PORT,
    db=settings.REDIS_DB,
    password=settings.REDIS_PASSWORD,
    decode_responses=True  # 自动解码为字符串
)

def get_redis():
    """获取Redis连接"""
    return redis.Redis(connection_pool=redis_pool)

class RedisClient:
    """Redis客户端工具类"""
    def __init__(self):
        self.redis = get_redis()
    
    def set(self, key: str, value: str, expire_seconds: int = None):
        """设置键值对，可选过期时间"""
        if expire_seconds:
            return self.redis.setex(key, expire_seconds, value)
        return self.redis.set(key, value)
    
    def get(self, key: str) -> str:
        """获取键值"""
        return self.redis.get(key)
    
    def delete(self, key: str):
        """删除键"""
        return self.redis.delete(key)
    
    def exists(self, key: str) -> bool:
        """判断键是否存在"""
        return self.redis.exists(key) == 1

# 创建Redis客户端实例
redis_client = RedisClient()
